package com.jia.netty.handler;

import com.google.gson.Gson;
import com.jia.entity.netty.ChartMsg;
import com.jia.entity.netty.CoonMsg;
import com.jia.entity.netty.HeardMsg;
import com.jia.entity.netty.NettyMsg;
import com.jia.netty.channel.ChannelGroup;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class WebSocketInChannelHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        String text = textWebSocketFrame.text();
        System.out.println("客户端发送的数据是："+text);

        Gson gson = new Gson();
        NettyMsg nettyMsg = gson.fromJson(text, NettyMsg.class);
        System.out.println(nettyMsg.getType());
        if(nettyMsg.getType() == 1){
            nettyMsg = gson.fromJson(text, CoonMsg.class);
        }else if(nettyMsg.getType() == 2){
            nettyMsg = gson.fromJson(text, HeardMsg.class);
        }else if(nettyMsg.getType() == 3){
            nettyMsg = gson.fromJson(text, ChartMsg.class);
        }


        channelHandlerContext.fireChannelRead(nettyMsg); //向下传递

    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("新客户端连接....");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端断开了....");
        ChannelGroup.removeChannel(ctx.channel());
    }
}
